<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="账期：" prop="payment_days">
              <el-date-picker
                v-model="form.payment_days"
                type="month"
                placeholder="选择月"
                value-format="yyyy-MM"
                @change="getArticleList"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="用户：" prop="uid">
              <change-user-input
                ref="changeUserInput"
                @sendValue="getUser"
                @clear="clearUid"
                @change="getArticleList"
              ></change-user-input>
            </el-form-item>
            <el-form-item label="单号：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="结算单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
              <el-button @click="exportbuVisible = true">导出</el-button>
            </MainFormBtn>

            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <el-form-item label="结算日期：" prop="createTime">
                  <el-date-picker
                    v-model="createTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>

                <el-form-item label="收款方式：" prop="pay_type">
                  <el-select
                    v-model.trim="form.pay_type"
                    placeholder="收款方式"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value="0"></el-option>
                    <el-option
                      v-for="(pay_type_list, index) in pay_type_list"
                      :key="index"
                      :label="pay_type_list"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="付款人：" prop="payuser">
                  <el-input
                    v-model.trim="form.payuser"
                    placeholder="付款人"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                  <el-select
                    v-model.trim="form.status"
                    placeholder="状态"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value="0"></el-option>
                    <el-option label="正常" value="2"></el-option>
                    <el-option label="作废" value="1"></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportbuVisible = true">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <router-link to="/financial/cashOrder/detail">
              <el-button> 结算明细</el-button>
            </router-link>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
          @row-dblclick="rowDblclick"
        >
          <!-- <el-table-column type="selection" :selectable="selectInit" /> -->
          <el-table-column label="结算单号" prop="order_sn" 
          :width="tableWidth[hash+'order_sn']"/>
          <el-table-column label="账期" prop="payment_days"
          :width="tableWidth[hash+'payment_days']">
            <template slot-scope="scope">
              {{ scope.row.payment_days }}
            </template>
          </el-table-column>

          <el-table-column label="用户名称" prop="nickname"
          :width="tableWidth[hash+'nickname']"> </el-table-column>
          <el-table-column label="收款金额" prop="collect_money"
          :width="tableWidth[hash+'collect_money']">
          </el-table-column>
          <el-table-column label="抹零金额" prop="zero_money" 
          :width="tableWidth[hash+'zero_money']"/>
          <el-table-column label="收款方式" prop="related_order_sn"
          :width="tableWidth[hash+'related_order_sn']">
            <template slot-scope="scope">
              <span :class="'type' + scope.row.pay_type">
                {{ pay_type_list[scope.row.pay_type] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status"
          :width="tableWidth[hash+'status']">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 0" style="color: #f56c6c">
                作废
              </span>
              <span v-else style="color: #03a98e"> 正常 </span>
            </template>
          </el-table-column>
          <el-table-column label="结算日期" prop="created_at"
          :width="tableWidth[hash+'created_at']">
            <template slot-scope="scope">
              {{ parseTime(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column
            label="管理操作"
            align="left"
            fixed="right"
            prop="operate"
            :width="tableWidth[hash+'operate'] || 240"
            class-name="main_hei handle"
            class="handle"
            label-class-name="main-center"
          >
            <template slot-scope="scope">
              <router-link :to="'/financial/cashOrder/see/' + scope.row.id"
                ><el-link type="success">查看</el-link></router-link
              >

              <el-link
                style="color: rgb(17, 138, 178)"
                @click="exportOrderiDetail(scope.row.id)"
                >导出</el-link
              >
              <el-link
                v-if="scope.row.status == 1"
                style="color: #f56c6c"
                @click="cancellation(scope.row.id)"
                >作废</el-link
              >
              <!--      <el-link style="color: #e47c02">打印</el-link> -->
            </template>
          </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 订单导出 -->
    <el-dialog
      title="货到付款结算单"
      :visible.sync="exportbuVisible"
      class="main_dialog dialog500"
    >
      <p class="exptitle">选择导出时间</p>
      <el-date-picker
        v-model="exportTime"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        @change="dateChange"
      >
      </el-date-picker>
      <el-tooltip
        class="item"
        effect="dark"
        content="时间范围只能选择两个月之内"
        placement="bottom"
      >
        <i class="el-icon-question"></i>
      </el-tooltip>
      <p class="exptitle" style="padding-top: 10px">用户</p>
      <change-user-input
        ref="changeUserInput_dia"
        @sendValue="
          (data) => {
            export_uid = data.info.user_id;
          }
        "
        @clear="export_uid = ''"
      ></change-user-input>

      <div slot="footer" class="dialog-footer">
        <el-button @click="exportbuVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleExport" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  offlineSettle_index,
  export_offlineSettle_list,
  export_offlineSettle_info,
  offline_setStatus,
} from "@/api/financial/finacialCashOnDelivery";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import rules from "@/rules/financial/financialReceivables";

export default {
  mixins: [mixins],
  data() {
    return {
      // 验证
      rules,
      // 时间
      parseTime,
      exportMethod,
      getNowMonth,
      listLoading: false,
      list: {
        data: [],
      },
      pay_type_list: {},
      typeList: {},
      // 搜索
      form: {
        payment_days: "", //账期
        order_sn: "", //单号
        uid: "",
        pay_type: null, //结算方式
        payuser: "",
        start_time: "", //结算日期
        end_time: "",
        status: "",
      },
      createTime: [],
      establishTime: [
        parseTime(new Date(), "{y}-{m}-{d}"),
        parseTime(new Date(), "{y}-{m}-{d}"),
      ],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 全选
      selectArr: [],
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      exportTime: [],
      export_uid: "",
      exportbuVisible: false,
    };
  },
  computed: {
    total() {
      let order = 0,
        send = 0,
        account = 0,
        diff = 0;
      this.list.data.forEach((e) => {
        order += parseFloat(this.$toFixed(parseFloat(e.order_money)));
        send += parseFloat(this.$toFixed(parseFloat(e.send_money)));
        account += parseFloat(this.$toFixed(parseFloat(e.account_money)));
      });

      order = this.$toFixed(order);
      send = this.$toFixed(send);
      account = this.$toFixed(account);
      diff = this.$toFixed(parseFloat(order - account));
      return { order, send, account, diff };
    },
  },
  activated() {
    this.getNumerical(200);
    // 列表
    this.offlineSettle_index();
  },
  created() {
    
  },
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      this.$router.push('/financial/cashOrder/see/' + row.id)
    },
    startGetting() {
      this.getSearchFor();
    },
    // 搜索并折叠搜索条件
    getSearchFor() {
      this.getArticleList();
    },
    // 作废订单
    cancellation(id) {
      console.log(id);
      this.$confirm("是否作废该订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          {
            id,
          }
        );
        offline_setStatus(data).then((res) => {
          if (!res.errcode) {
            this.$message({
              type: "success",
              message: "作废成功",
            });
            this.offlineSettle_index();
          } else {
            this.$message({
              type: "error",
              message: res.errmsg,
            });
          }
        });
      });
    },
    //获取用户信息
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      this.offlineSettle_index();
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
    },
    // 订单差额 ？注释
    renderHeader_purchase(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "注释：差异金额=下单金额-账单金额",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    // 监听绑定全选不可勾选
    selectInit(row, index) {
      return true;
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push(item.id);
      });
    },

    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.offlineSettle_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.createTime = [];
      this.$refs["changeUserInput"].name = "";
      this.offlineSettle_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.offlineSettle_index();
    },
    changePage(page) {
      this.current.page = page;
      this.offlineSettle_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    offlineSettle_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      offlineSettle_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data.list;
          this.pay_type_list = res.data.pay_type_list;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      return form;
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (index) {
          case 1:
            sums[index] = "合计";
            break;
          case 7:
            sums[index] = this.total.order;
            break;
          case 8:
            sums[index] = this.total.send;
            break;
          case 10:
            sums[index] = this.total.account;
            break;
          case 11:
            sums[index] = this.total.diff;
            break;
        }
      });

      return sums;
    },
    // 列表导出
    exportOrderiInfo(form) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_offlineSettle_list(data)
        .then((res) => {
          this.exportMethod(res, "货到付款结算单列表", notify);
        })
        .catch((err) => {
          this.$message.error("导出失败");
        });
    },
    // 导出
    handleExport() {
      if (this.exportTime.length == 0) {
        this.$message.warning("请选择需要导出的时间段");
        return;
      }
      let form = {
        start_time: "",
        end_time: "",
        uid: this.export_uid,
      };

      if (this.exportTime && this.exportTime.length > 0) {
        form.start_time = this.exportTime[0];
        form.end_time = this.exportTime[1];
      }
      this.exportOrderiInfo(form);
      if (this.$refs["changeUserInput_dia"]) {
        this.$refs["changeUserInput_dia"].name = "";
      }
      this.exportbuVisible = false;
      this.$nextTick(() => {
        this.exportTime = [];
        this.uid = "";
      });
    },
    // 日期选择
    dateChange(val) {
      let start = val ? new Date(val[0]).getTime() : 0;
      let end = val ? new Date(val[1]).getTime() : 0;
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.exportTime = this.getNowMonth();
      }
    },
    // 详情导出
    exportOrderiDetail(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_offlineSettle_info(data)
        .then((res) => {
          this.exportMethod(res, "货到付款结算单详情", notify);
        })
        .catch((err) => {
          this.$message.error("导出失败");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: 100%;
  }

  .main_dialog {
    .main_xq {
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 0;
      }
    }

    .main_table {
      /deep/.el-table__body-wrapper {
        overflow-y: auto;
        height: 400px;
      }
      /deep/.el-table--small td {
        padding-top: 0;
      }
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 16px;
        margin-top: 16px;
        margin-right: 0;
      }
    }
    .main_xq ul li {
      width: 33.33%;
      margin-top: 5px;
      margin-bottom: 5px;
      .main_xqs {
        width: 85%;
        display: block;
        text-align: left;
        /deep/.el-input--small {
          width: 100%;
        }
      }
    }
    .footer_red {
      font-size: 16px;
      color: red;
      margin-right: 10px;
    }
  }
}
.type1 {
  color: #03a98e;
}
.type2 {
  color: #e47c02;
}
.type3 {
  color: rgb(17, 138, 178);
}
.type4 {
  color: rgb(170, 205, 110);
}

/deep/.main_table .el-table--small td.handle .cell {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.new_navbar_svg {
  vertical-align: top;
  margin-left: 5px;
  use {
    fill: #606266;
  }
}
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
  cursor: pointer;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
